<template>
    <v-container fluid>
        <v-card class="elevation-10">
            <v-card-title class="d-flex align-center pa-4">
                <div class="d-flex align-center gap-2">
                    <v-btn color="primary" prepend-icon="mdi-plus" @click="handleAdd" 
                        v-if="$perms('tenant_statusrule_insert')"
                        >
                        新增规则
                    </v-btn>

                    <v-btn color="error" variant="outlined" :disabled="!selectRows.length" @click="handleDeleteBatch"
                        icon="mdi-delete" size="small" 
                        v-if="$perms('tenant_statusrule_delete')"
                        />

                    <v-btn 
                        v-if="$perms('tenant_statusrule_export')"
                        color="success"
                        variant="outlined" @click="handleExport" size="small" icon="mdi-download" />
                </div>

                <v-spacer />

                <!-- 搜索区域 -->
                <div class="d-flex align-center gap-2">
                    <v-text-field v-model="queryParams.eventName_LIKE"
                        label="事件名称" variant="outlined" density="compact" clearable hide-details
                        style="width: 120px;" class="mr-2" />
                    <v-text-field v-model="queryParams.eventCode_LIKE"
                        label="事件代码" variant="outlined" density="compact" clearable hide-details
                        style="width: 120px;" class="mr-2" />

                    <v-btn variant="outlined" @click="resetQuery" class="mr-2">
                        <v-icon start>mdi-refresh</v-icon>
                        重置
                    </v-btn>

                    <v-btn type="submit" color="primary" variant="flat" @click="fetchData" class="mr-2">
                        <v-icon start>mdi-magnify</v-icon>
                        搜索
                    </v-btn>

                    <v-btn variant="outlined" @click="toggleMoreQuery">
                        <v-icon start>{{ showMoreQuery ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
                        更多
                    </v-btn>
                </div>
            </v-card-title>

            <!-- 更多查询条件 -->
            <v-expand-transition>
                <v-card-text v-show="showMoreQuery" class="pt-0">
                    <v-divider class="mb-4"></v-divider>
                    <v-row>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.isActive_EQ"
                                :items="activeOptions" label="启用状态" variant="outlined" density="compact" 
                                clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.isAuto_EQ"
                                :items="autoOptions" label="自动流转" variant="outlined" density="compact" 
                                clearable hide-details />
                        </v-col>
                    </v-row>
                </v-card-text>
            </v-expand-transition>

            <!-- 数据表格 -->
            <v-data-table v-model="selectRows" :headers="headers" :items="dataList" :loading="loading"
                :items-length="total" :items-per-page="queryParams.pageSize" :page="queryParams.pageNo" show-select
                item-value="id" @update:page="handlePageChange" @update:items-per-page="handlePageSizeChange"
                @update:model-value="setSelectRows">

                <!-- 自动流转列 -->
                <template #item.isAuto="{ item }">
                    <v-chip :color="item.isAuto === 1 ? 'primary' : 'info'" size="small" variant="outlined">
                        {{ item.isAuto === 1 ? '是' : '否' }}
                    </v-chip>
                </template>

                <!-- 是否启用列 -->
                <template #item.isActive="{ item }">
                    <v-switch :model-value="item.isActive === 1" 
                        @update:model-value="handleToggleActive(item)" 
                        color="primary" hide-details density="compact"
                        />
                </template>

                <!-- 操作列 -->
                <template #item.actions="{ item }">
                    <div class="d-flex gap-1">
                        <v-btn size="small" color="primary" variant="text" icon="mdi-pencil"
                            @click="handleEdit(item)" v-if="$perms('tenant_statusrule_update')" />
                        <v-btn size="small" color="error" variant="text" icon="mdi-delete"
                            @click="handleDelete(item)" v-if="$perms('tenant_statusrule_delete')" />
                        <v-btn size="small" color="info" variant="text" icon="mdi-play"
                            @click="handleTestRule(item)" title="测试规则" />
                    </div>
                </template>
            </v-data-table>
        </v-card>

        <!-- 编辑对话框 -->
        <TenantStatusRuleEdit ref="editRef" @fetch-data="fetchData" />

        <!-- 测试规则对话框 -->
        <v-dialog v-model="testDialog" max-width="600px">
            <v-card>
                <v-card-title>测试规则执行</v-card-title>
                <v-card-text>
                    <v-form ref="testFormRef">
                        <v-row>
                            <v-col cols="12">
                                <v-text-field
                                    v-model="testForm.customerId"
                                    label="客户ID"
                                    variant="outlined"
                                    density="compact"
                                    required
                                />
                            </v-col>
                            <v-col cols="12">
                                <v-textarea
                                    v-model="testForm.eventData"
                                    label="事件数据(JSON格式)"
                                    variant="outlined"
                                    rows="4"
                                    placeholder='{"amount": 1000, "course": "数学"}'
                                />
                            </v-col>
                        </v-row>
                    </v-form>
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn color="grey-darken-1" variant="text" @click="testDialog = false">
                        取消
                    </v-btn>
                    <v-btn color="primary" variant="text" @click="confirmTestRule" :loading="testLoading">
                        执行测试
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {
    getList,
    doDelete,
    doDeleteAll,
    doExportExcel,
    doUpdate,
    type TenantStatusRuleModel,
    type TenantStatusRuleQueryParams,
    type ApiResponse,
    type PageResult
} from '@/api/tenant/customerstatus/TenantStatusRuleManagementApi';
import TenantStatusRuleEdit from './components/TenantStatusRuleEdit.vue';
import { useMessage } from '@/composables/useMessage';
import { useConfirm } from '@/composables/useConfirm';

const { success: showSuccess, error: showError } = useMessage();
const { confirmDelete } = useConfirm();

// 基础数据
const loading = ref(false);
const dataList = ref<TenantStatusRuleModel[]>([]);
const total = ref(0);
const selectRows = ref<string[]>([]);
const editRef = ref();
const showMoreQuery = ref(false);

// 测试规则相关
const testDialog = ref(false);
const testLoading = ref(false);
const testFormRef = ref();
const currentTestRule = ref<TenantStatusRuleModel | null>(null);
const testForm = reactive({
    customerId: '',
    eventData: ''
});

// 查询参数
const queryParams = reactive<TenantStatusRuleQueryParams>({
    pageNo: 1,
    pageSize: 10,
    eventName_LIKE: undefined,
    eventCode_LIKE: undefined,
    isActive_EQ: undefined,
    isAuto_EQ: undefined,
});

// 选项数据
const activeOptions = [
    { title: '启用', value: 1 },
    { title: '禁用', value: 0 }
];

const autoOptions = [
    { title: '是', value: 1 },
    { title: '否', value: 0 }
];

// 表格列定义
const headers = computed(() => [
    {
        title: '事件代码',
        key: 'eventCode',
        sortable: false,
        width: 150,
    },
    {
        title: '事件名称',
        key: 'eventName',
        sortable: false,
    },
    {
        title: '源状态',
        key: 'fromStatus',
        sortable: false,
        width: 100,
    },
    {
        title: '目标状态',
        key: 'toStatus',
        sortable: false,
        width: 100,
    },
    {
        title: '自动流转',
        key: 'isAuto',
        sortable: false,
        width: 100,
    },
    {
        title: '触发条件',
        key: 'conditions',
        sortable: false,
    },
    {
        title: '排序号',
        key: 'sortOrder',
        sortable: false,
        width: 100,
    },
    {
        title: '是否启用',
        key: 'isActive',
        sortable: false,
        width: 100,
    },
    {
        title: '操作',
        key: 'actions',
        sortable: false,
        width: 150,
    },
]);

// 获取数据
async function fetchData() {
    try {
        loading.value = true;
        const response: ApiResponse<PageResult<TenantStatusRuleModel>> = await getList(queryParams);
        if (response.code === 200) {
            dataList.value = response.data.rows || [];
            total.value = response.data.total || 0;
        }
    } catch (error) {
        console.error('获取数据失败:', error);
        showError('获取数据失败');
    } finally {
        loading.value = false;
    }
}

// 重置查询
function resetQuery() {
    Object.assign(queryParams, {
        pageNo: 1,
        pageSize: 10,
        eventName_LIKE: undefined,
        eventCode_LIKE: undefined,
        isActive_EQ: undefined,
        isAuto_EQ: undefined,
    });
    fetchData();
}

// 切换更多查询
function toggleMoreQuery() {
    showMoreQuery.value = !showMoreQuery.value;
}

// 页码变化
function handlePageChange(page: number) {
    queryParams.pageNo = page;
    fetchData();
}

// 每页数量变化
function handlePageSizeChange(size: number) {
    queryParams.pageSize = size;
    queryParams.pageNo = 1;
    fetchData();
}

// 设置选中行
function setSelectRows(rows: string[]) {
    selectRows.value = rows;
}

// 新增
function handleAdd() {
    editRef.value?.showEdit();
}

// 编辑
function handleEdit(row: TenantStatusRuleModel) {
    editRef.value?.showEdit(row);
}

// 删除
async function handleDelete(row: TenantStatusRuleModel) {
    const confirmed = await confirmDelete('确定要删除这个规则吗？');
    if (!confirmed) return;

    try {
        const response = await doDelete({ id: row.id! });
        if (response.code === 200) {
            showSuccess('删除成功');
            fetchData();
        }
    } catch (error) {
        console.error('删除失败:', error);
        showError('删除失败');
    }
}

// 批量删除
async function handleDeleteBatch() {
    const confirmed = await confirmDelete(`确定要删除选中的 ${selectRows.value.length} 个规则吗？`);
    if (!confirmed) return;

    try {
        const response = await doDeleteAll({ ids: selectRows.value.join(',') });
        if (response.code === 200) {
            showSuccess('批量删除成功');
            selectRows.value = [];
            fetchData();
        }
    } catch (error) {
        console.error('批量删除失败:', error);
        showError('批量删除失败');
    }
}

// 切换启用状态
async function handleToggleActive(item: TenantStatusRuleModel) {
    try {
        const newStatus = item.isActive === 1 ? 0 : 1;
        const updateData = { ...item, isActive: newStatus };
        
        const response = await doUpdate(updateData);
        if (response.code === 200) {
            item.isActive = newStatus;
            showSuccess(newStatus === 1 ? '启用成功' : '禁用成功');
        }
    } catch (error) {
        console.error('切换状态失败:', error);
        showError('切换状态失败');
    }
}

// 测试规则
function handleTestRule(row: TenantStatusRuleModel) {
    currentTestRule.value = row;
    testForm.customerId = '';
    testForm.eventData = '{}';
    testDialog.value = true;
}

// 确认测试规则
async function confirmTestRule() {
    if (!currentTestRule.value) return;
    
    try {
        testLoading.value = true;
        
        // 这里调用后端测试接口
        // const response = await testRule({
        //     ruleId: currentTestRule.value.id,
        //     customerId: testForm.customerId,
        //     eventData: JSON.parse(testForm.eventData || '{}')
        // });
        
        showSuccess('规则测试执行成功');
        testDialog.value = false;
    } catch (error) {
        console.error('测试规则失败:', error);
        showError('测试规则失败');
    } finally {
        testLoading.value = false;
    }
}

// 导出Excel
async function handleExport() {
    try {
        await doExportExcel(queryParams);
        showSuccess('导出成功');
    } catch (error) {
        console.error('导出失败:', error);
        showError('导出失败');
    }
}

// 生命周期
onMounted(() => {
    fetchData();
});
</script>

<style lang="scss" scoped>
:deep(.v-data-table) {
    .v-data-table__td {
        padding: 8px 16px;
    }
}
</style> 